/*
 * Copyright (C) 2021 The Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.oushangfeng.pinneddemo.slice;

import com.oushangfeng.pinneddemo.ResourceTable;
import com.oushangfeng.pinneddemo.adapter.CategoryListItemProvider;
import com.oushangfeng.pinneddemo.custom.categorylist.HeadItem;
import com.oushangfeng.pinneddemo.custom.data.CustomData;
import com.oushangfeng.pinnedsectionitemdecoration.callback.datainterface.Category;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.util.List;

/**
 * SharesDemoAbilitySlice
 *
 * @since 2021-04-19
 *
 */
public class SharesDemoAbilitySlice extends AbilitySlice {
    private static final int UPSCROLL = 1;
    private static final int DOWNSCROLL = 2;
    private static final HiLogLabel PINNED = new HiLogLabel(HiLog.LOG_APP,0x00201,"PinnedSectionItemDecoration");
    private static final float OLD_SHOW_TEXT_Y_DEFAULT = -1;
    private static final int Y_DEFAULT = 10;
    private static final int NUM_2 = 2;
    private static final int NUM_3 = 3;
    private static final int NUM_11 = 11;
    float oldShowTextY = OLD_SHOW_TEXT_Y_DEFAULT;
    float showTextY = 0;
    float titleBarY = 0;
    float downY = 0;
    Context context;
    int scrollType = 0;

    // 判断上滑是否回弹
    boolean isScroll = false;
    boolean isCheck = false;
    boolean isShow = true;
    private DependentLayout showDependent;
    private ListContainer listContainer;
    private Text showHeaderItemContentText;
    private List<Category> cacheCategoryList;
    private List<Category> categoryList;
    private boolean isChangeTitle = false;
    private boolean isNotify = true;

    // 缓存被更改的原标签的数组下标
    private int cacheShowListNum = 0;

    // 缓存被更改下标的原数组的具体值的下标
    private int cacheShowList = 0;

    // 缓存刷新的数据源的下标
    private int cacheIndex = 0;
    private String cacheTitle = "涨幅榜";
    private Image image;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_shares_demo);
        context = SharesDemoAbilitySlice.this;
        initView();
    }

    private void initView() {
        CustomData customData = new CustomData();
        showDependent = (DependentLayout) findComponentById(ResourceTable.Id_show_stock_header_layout);
        image = (Image) findComponentById(ResourceTable.Id_check_stock1);
        image.setClickedListener(component -> {
            if (isCheck) {
                isCheck = false;
                image.setPixelMap(ResourceTable.Media_unchecked1);
            } else {
                isCheck = true;
                image.setPixelMap(ResourceTable.Media_checked1);
            }
        });
        showHeaderItemContentText = (Text) findComponentById(ResourceTable.Id_show_header_stock_text);
        if (listContainer == null) {
            listContainer = (ListContainer) findComponentById(ResourceTable.Id_lc_shares_list);
            categoryList = customData.getStockData(context);
            cacheCategoryList = customData.getStockData(context);
            CategoryListItemProvider categoryListItemProvider = new CategoryListItemProvider(categoryList);
            listContainer.setItemProvider(categoryListItemProvider);

        }
        listContainer.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                int action = touchEvent.getAction();
                MmiPoint point = touchEvent.getPointerPosition(touchEvent.getIndex());
                switch (action) {
                    case TouchEvent.PRIMARY_POINT_DOWN:
                        downY = point.getY();
                        return true;
                    case TouchEvent.POINT_MOVE:
                        if (point.getY() > downY) {
                            scrollType = UPSCROLL;
                        } else {
                            scrollType = DOWNSCROLL;
                        }
                        downY = point.getY();
                        break;
                    case TouchEvent.PRIMARY_POINT_UP:
                        downY = 0;
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

        listContainer.setScrolledListener((component, i, i1, i2, i3) -> {
            if (scrollType == UPSCROLL) {
                upMove();
            } else if (scrollType == DOWNSCROLL) {
                downMove();
            }
        });
    }

    private void downMove() {
        if (!isShow) {
            isShow = true;
        }
        if (oldShowTextY == OLD_SHOW_TEXT_Y_DEFAULT) {
            oldShowTextY = showDependent.getContentPositionY();
        }

        // 获取当前屏幕完整显示的第1个item的下标
        int index = listContainer.getItemPosByVisibleIndex(1);

        // 当前展示的列表的下标
        int showList = getListItem(index);

        // 当前展示的列表的元素的下标
        int showListNum = getListNum(index);

        if (index > 1) {
            showDependent.setVisibility(Component.VISIBLE);
        }

        if (categoryList.get(showList).getCategoryItemType(showListNum) == HeadItem.ITEM_TYPE) {
            isChangeTitle = true;

            // 当第一个显示的是标题栏的话就记录Y轴位置
            Component firstComponent = listContainer.getComponentAt(index);

            // 标题栏的下Y轴坐标位置
            double showTextOldY = (double)showDependent.getContentPositionY() + (double) showDependent.getHeight();

            // 记录标题栏的上Y轴值
            int firstComponentTop = firstComponent.getTop();

            // 如果最上方展示text的下Y轴对应上滑上来的标题栏的上Y轴就记录位置
            if (showTextOldY - (double)firstComponentTop < Y_DEFAULT) {
                showTextY = (float) showTextOldY;
                titleBarY = firstComponentTop;
            }

            // 如果展示的text的下Y轴大于标题栏的上Y轴就让展示的text的Y轴移动
            if (firstComponentTop > showTextOldY) {
                double titlBarDifferenceY = (double)titleBarY - (double)firstComponentTop;
                showDependent.setContentPositionY((float) (showTextY - titlBarDifferenceY - showDependent.getHeight()));
            }
        } else {
            showDependent.setContentPositionY(0);
            if (isChangeTitle) {
                HiLog.info(PINNED,"show_list=" + showList);
                showHeaderItemContentText.setText(categoryList.get(showList).getItemVaule(0));
                isChangeTitle = false;
            }
        }
    }

    private int getListNum(int index) {
        if (index < NUM_2) {
            return 0;
        } else {
            return (index - NUM_2) % NUM_11;
        }
    }

    private int getListItem(int index) {
        if (index < NUM_2) {
            return index;
        } else {
            return (index - NUM_2) / NUM_11 + 1;
        }
    }

    private void upMove() {
        int index = listContainer.getItemPosByVisibleIndex(0);
        if (index < NUM_3) {
            showDependent.setVisibility(Component.HIDE);
        }
        if (showDependent.getContentPositionY() < oldShowTextY) {
            downMove();
        } else {
            // 当前展示的列表的下标
            int showList = getListItem(index);

            // 当前展示的列表的元素的下标
            int showListNum = getListNum(index);
            int laterType = categoryList.get(showList).getCategoryItemType(showListNum);
            Component firstComponent = listContainer.getComponentAt(index);
            if (laterType == HeadItem.ITEM_TYPE) {
                if (isNotify) {
                    if (showList > 1) {
                        cacheTitle = categoryList.get(showList - 1).getItemVaule(showListNum);
                    } else {
                        cacheTitle = categoryList.get(showList).getItemVaule(showListNum);
                    }
                    categoryList.get(showList).setItemVaule(showListNum,cacheTitle);
                    listContainer.getItemProvider().notifyDataSetItemChanged(index);
                    cacheShowList = showList;
                    cacheShowListNum = showListNum;
                    cacheIndex = index;
                    isNotify = false;
                }
                isScroll = true;
                if (firstComponent != null) {
                    showDependent.setContentPositionY((float) ((double)firstComponent.getContentPositionY()
                                                + (double)firstComponent.getHeight()));
                }
            } else {
                showDependent.setContentPositionY(0);
                int index1 = index + 1;

                // 当前展示的列表的下标
                int showList1 = getListItem(index1);

                // 当前展示的列表的元素的下标
                int showListNum1 = getListNum(index1);
                int laterType1 = categoryList.get(showList1).getCategoryItemType(showListNum1);
                if (laterType1 == HeadItem.ITEM_TYPE) {
                    showHeaderItemContentText.setText(cacheTitle);
                    if (isScroll) {
                        isScroll = false;

                        // 标签值还原
                        categoryList.get(cacheShowList).setItemVaule(
                                cacheShowListNum,cacheCategoryList.get(cacheShowList).getItemVaule(0));
                        listContainer.getItemProvider().notifyDataSetItemChanged(cacheIndex);
                        listContainer.scrollTo(0, showDependent.getHeight());
                        isNotify = true;
                    }
                }
            }
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
